<template>
  <div class="question-space-container">
    <div class="question-space">
      <!-- 返回按钮 和 标题 -->
      <div class="header">
        <div class="back-button" @click="goBack">
          <i class="el-icon-arrow-left"></i>
        </div>
        <h1 class="title">全部评论</h1>
        <div class="share-icon">
          <i class="el-icon-share"></i>
        </div>
      </div>

      <!-- 原问题标题 -->
      <div class="question-detail-container" v-if="questionDetail">
        <h2 class="question-title">{{ questionDetail.title }}</h2>
      </div>

      <!-- 一级回答详情 -->
      <div class="question-detail-container" v-if="answerDetail">
        <div class="user-info">
          <div class="avatar">
            <img :src="answerDetail.avatar || defaultAvatar" alt="用户头像"/>
          </div>
          <span class="username">{{ answerDetail.publisher }}</span>
        </div>

        <div class="question-content">
          <div class="question-description">{{ answerDetail.content }}</div>
          <div class="publish-time" v-if="answerDetail && answerDetail.publishTime">
            发布于{{ formatTime(answerDetail.publishTime) }}
          </div>
        </div>
      </div>

      <!-- 分隔线 -->
      <div class="divider"></div>

      <!-- 全部评论标题 -->
      <div class="answer-title">全部评论</div>

      <!-- 评论列表区域 -->
      <div class="answer-list-container">
        <div v-if="!loading && commentList.length === 0" class="no-answers">
          暂无评论
        </div>

        <div v-else class="answer-list">
          <div v-for="comment in commentList" :key="comment.id" class="answer-card">
            <div class="user-info">
              <div class="avatar">
                <img :src="comment.avatar || defaultAvatar" alt="用户头像"/>
              </div>
              <div class="user-meta">
                <span class="username">{{ comment.publisher }}</span>
                <span class="publish-time">{{ formatTime(comment.publishTime) }}</span>
              </div>
            </div>
            <div class="answer-content">
              {{ comment.content }}
            </div>
          </div>
        </div>
      </div>

      <!-- 评论输入框 -->
      <div class="answer-input-container">
        <el-input
            v-model="commentContent"
            type="textarea"
            :maxlength="400"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="说点什么吧~"
            show-word-limit
        ></el-input>
        <el-button
            type="primary"
            class="send-button"
            :disabled="!commentContent.trim()"
            @click="submitComment"
        >
          发送
        </el-button>
      </div>

      <!-- 全键盘区域 -->
      <div class="keyboard-area">
        <div class="keyboard-hint">字母全键盘区</div>
      </div>
    </div>
  </div>
</template>

<script>
import { sendRequest } from '@/util/request';

export default {
  name: 'AnswerDetail',
  data() {
    return {
      quesId: null,       // 问题ID
      answerId: null,     // 回答ID
      questionDetail: null, // 问题详情
      answerDetail: null, // 回答详情
      commentList: [],    // 评论列表
      userMap: new Map(), // 存储用户信息
      commentContent: '', // 评论内容
      loading: false,
      defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
    };
  },
  created() {
    // 从路由获取问题ID和回答ID
    this.quesId = this.$route.query.quesId;
    this.answerId = this.$route.query.answerId;

    console.log('当前查看的问题ID:', this.quesId, '回答ID:', this.answerId);

    if (this.quesId && this.answerId) {
      // 先加载用户数据，然后获取问题详情和回答列表
      Promise.all([
        this.loadUserData(),
        this.getQuestionDetail(),
        this.getAnswerDetail(),
        this.getCommentList()
      ]).catch(error => {
        console.error('初始化数据失败:', error);
      });
    } else {
      this.$message.error('参数不完整');
      this.goBack();
    }
  },
  methods: {
    // 加载用户数据
    async loadUserData() {
      try {
        const res = await sendRequest('get', '/user/list');
        if (res.code === 200) {
          const users = res.rows || [];
          // 创建用户ID到用户信息的映射
          users.forEach(user => {
            this.userMap.set(user.userId, user);
          });
        }
      } catch (error) {
        console.error('获取用户数据失败:', error);
      }
    },

    // 获取问题详情
    async getQuestionDetail() {
      try {
        const res = await sendRequest('get', `/ques/${this.quesId}`);
        if (res.code === 200) {
          this.questionDetail = res.data;
        } else {
          this.$message.error('获取问题详情失败');
        }
      } catch (error) {
        console.error('获取问题详情失败:', error);
      }
    },

    // 获取回答详情
    async getAnswerDetail() {
      this.loading = true;
      try {
        // 获取回答列表，然后找到当前回答
        const params = { quesId: this.quesId };
        const res = await sendRequest('get', '/answer/list', params);

        if (res.code === 200) {
          // 找到当前回答
          const answer = (res.rows || []).find(item =>
              item.id === this.answerId ||
              item.id === parseInt(this.answerId)
          );

          if (answer) {
            this.answerDetail = answer;

            // 获取发布者头像
            if (answer.userId) {
              const userInfo = this.userMap.get(parseInt(answer.userId));
              if (userInfo) {
                answer.avatar = userInfo.avatar;
              }
            }
          } else {
            this.$message.error('未找到回答详情');
          }
        } else {
          this.$message.error('获取回答详情失败');
        }
      } catch (error) {
        console.error('获取回答详情失败:', error);
        this.$message.error('获取回答详情失败');
      } finally {
        this.loading = false;
      }
    },

    // 获取评论列表
    async getCommentList() {
      try {
        // 使用回答列表接口，筛选出该回答的二级回答
        const params = { quesId: this.quesId };

        const res = await sendRequest('get', '/answer/list', params);
        if (res.code === 200) {
          // 筛选出所有parentId等于当前回答id的回答，这些就是二级回答
          const comments = res.rows.filter(reply =>
              reply.parentId === this.answerId ||
              reply.parentId === parseInt(this.answerId)
          );

          // 为每个评论添加用户信息
          for (let i = 0; i < comments.length; i++) {
            const comment = comments[i];

            // 获取评论者头像
            if (comment.userId) {
              const userInfo = this.userMap.get(parseInt(comment.userId));
              if (userInfo) {
                comment.avatar = userInfo.avatar;
              }
            }
          }

          // 按照时间倒序排序
          this.commentList = comments.sort((a, b) =>
              new Date(b.publishTime) - new Date(a.publishTime)
          );
        }
      } catch (error) {
        console.error('获取评论列表失败:', error);
      }
    },

    // 提交评论
    async submitComment() {
      if (!this.commentContent.trim()) {
        this.$message.warning('请输入内容');
        return;
      }

      this.loading = true;
      try {
        // 获取用户信息，如果没有则使用默认值
        const userInfo = JSON.parse(localStorage.getItem('userInfo')) || {};
        const publisher = userInfo.username || 'anonymous';
        const phone = userInfo.phone || '00000000000';

        // 准备评论数据
        const commentData = {
          quesId: this.questionId,     // 问题ID
          parentId: this.answerId,      // 父回答ID
          content: this.commentContent.trim(),
          publisher: publisher,
          phone: phone
        };

        console.log('提交评论:', commentData);

        const res = await sendRequest('post', '/answer', commentData);
        if (res.code === 200) {
          this.$message.success('评论发送成功');
          this.commentContent = ''; // 清空输入框

          // 立即添加新评论到列表中
          const newComment = {
            id: res.data || Date.now(), // 使用后端返回的ID或临时ID
            quesId: this.questionId,
            parentId: this.answerId,
            content: commentData.content,
            publisher: commentData.publisher,
            publishTime: new Date().toISOString(),
            avatar: this.defaultAvatar
          };

          // 添加到列表顶部
          this.commentList.unshift(newComment);

          // 同时刷新完整列表以确保数据一致性
          setTimeout(() => {
            this.getCommentList();
          }, 500);
        } else {
          this.$message.error('发送失败，请重试');
        }
      } catch (error) {
        console.error('提交评论失败:', error);
        this.$message.error('发送失败，请重试');
      } finally {
        this.loading = false;
      }
    },

    // 返回上一页
    goBack() {
      this.$router.push({
        path: '/ques/detail',
        query: { id: this.quesId }
      });
    },

    formatTime(time) {
      // 如果没有时间数据，返回空字符串
      if (!time) return '';

      try {
        // 处理LocalDateTime格式，通常格式为："2023-11-30T14:30:45"
        // 或其他ISO格式字符串
        const dateStr = String(time);

        // 尝试提取年月日
        // 方法一：使用正则表达式
        const match = dateStr.match(/(\d{4})-(\d{2})-(\d{2})/);
        if (match) {
          return `${match[1]}年${match[2]}月${match[3]}日`;
        }

        // 方法二：使用Date对象（如果后端返回的是标准ISO格式）
        const date = new Date(time);
        if (!isNaN(date.getTime())) {
          return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
        }

        // 方法三：手动解析（如果格式特殊）
        const parts = dateStr.split(/[-T]/);
        if (parts.length >= 3) {
          return `${parts[0]}年${parts[1]}月${parts[2].substring(0, 2)}日`;
        }

        return dateStr; // 如果无法解析，返回原始字符串
      } catch (e) {
        console.error('日期格式化错误:', e, time);
        return String(time); // 发生错误时返回原始值
      }
    }
  }
};
</script>

<style scoped>
.question-space-container {
  display: flex;
  justify-content: center;
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.question-space {
  position: relative;
  width: 33.33%;
  height: 100vh;
  background-color: #fff;
  background-image: url('E:/zhizhiniao1-ui/bird1-ui/src/assets/re_8640_userlmn_566c912f88a7.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.header {
  position: sticky;
  top: 0;
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: transparent;
  z-index: 20;
  text-align: center;
  position: relative;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.back-button {
  position: absolute;
  left: 15px;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.title {
  margin: 0 auto;
  font-size: 20px;
  font-weight: bold;
  color: #333;
  width: 100%;
  text-align: center;
}

.share-icon {
  position: absolute;
  right: 15px;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

/* 问题详情容器 */
.question-detail-container {
  padding: 15px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  margin: 10px;
}

.question-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 10px;
  background-color: #eee;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.username {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.question-content {
  margin-bottom: 15px;
}

.question-description {
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  margin-bottom: 10px;
  word-break: break-all;
}

.publish-time {
  font-size: 12px;
  color: #999;
  margin-top: 10px;
}

.divider {
  height: 1px;
  background-color: rgba(0, 0, 0, 0.1);
  margin: 15px 0;
}

.answer-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 15px;
}

/* 回答列表容器 */
.answer-list-container {
  flex: 1;
  overflow-y: auto;
  padding: 0 15px;
}

.no-answers {
  text-align: center;
  padding: 30px 0;
  color: #999;
}

.answer-card {
  padding: 15px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  margin-bottom: 15px;
}

.user-meta {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.publish-time {
  font-size: 12px;
  color: #999;
}

.answer-content {
  margin-top: 10px;
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  word-break: break-all;
}

/* 输入框 */
.answer-input-container {
  position: sticky;
  bottom: 40px;
  padding: 15px;
  background-color: rgba(255, 255, 255, 0.95);
  display: flex;
  align-items: center;
}

.send-button {
  margin-left: 10px;
  height: 38px;
}

/* 键盘区域 */
.keyboard-area {
  position: sticky;
  bottom: 0;
  height: 40px;
  background-color: #f5f5f5;
  display: flex;
  justify-content: center;
  align-items: center;
  border-top: 1px solid #e0e0e0;
}

.keyboard-hint {
  font-size: 12px;
  color: #666;
}

/* Element UI 样式覆盖 */
.el-textarea >>> .el-textarea__inner {
  background-color: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(0, 0, 0, 0.1);
  resize: none;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .question-space {
    width: 50%;
  }
}

@media (max-width: 768px) {
  .question-space {
    width: 95%;
  }
}
</style>
